package com.itheima.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Author 小帅蓝
 * @Date 2022/6/19 14:12
 * OSS文件上传工具类
 */
public class OssUtils {

    /**
     * Endpoint
     */
    private static String endpoint = "http://oss-cn-guangzhou.aliyuncs.com";
    /**
     * 云账号AccessKey有所有API访问权限
     */
    private static final String accessKeyId = "LTAI5tJYK1Wk2XpJAFNEJaKZ";
    private static final String accessKeySecret = "tKORmzBqMc2bew1UZyCcSaJx3iR38F";
    private static final String bucketName = "lan-test-01";
    private final static String URL="\n" +"https://lan-test-01.oss-cn-guangzhou.aliyuncs.com/";

    //目录名
    public static String dir = "reggie/";

    /**
     * 文件上传
     *
     * @param inputStream inputStream
     * @param fileName fileName
     */
    public static String upload(InputStream inputStream, String fileName) {
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        oss.putObject(bucketName, dir + fileName, inputStream);

        oss.shutdown();
        String ossUrl = URL + dir + fileName;

        System.out.println("图片地址" + ossUrl);

        return ossUrl;
    }


    /**
     * 文件下载
     *
     * @param filename
     * @param response
     * @throws IOException
     */
    public static void download(String filename, HttpServletResponse response) throws IOException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 调用ossClient.getObject返回一个OSSObject实例，该实例包含文件内容及文件元信息。
        OSSObject ossObject = ossClient.getObject(bucketName, filename);
        //通过输出流，输出文件内容
        ServletOutputStream outputStream = response.getOutputStream();
        //设置输出文件的格式
        response.setContentType("/image/jpeg");
        InputStream content = ossObject.getObjectContent();
        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = content.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
            outputStream.flush();
        }
        content.close();
    }

}
